import { createRouter, createWebHistory } from 'vue-router'
import { localCache } from '@/utils/cache'
import { firstMenu } from '@/utils/map-menus'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/main'
    },
    {
      path: '/login',
      name: 'login',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/login/index.vue')
    },
    {
      path: '/main',
      name: 'main',
      component: () => import('@/views/main/index.vue'),
      children: [
        // {
        //   path: '/home',
        //   name: 'home',
        //   component: () => import('@/views/main/home/index.vue')
        // }
      ]
    },
    {
      path: '/:pathMatch(.*)', // 匹配所有路径
      // name: 'notFound',
      component: () => import('../views/notFound/index.vue')
    }
  ]
})

// 导航守卫
router.beforeEach((to) => {
  const token = localCache.getCache('token')
  if (to.path !== '/login' && !token) {
    return '/login'
  }

  // 动态匹配第一个菜单
  if (to.path === '/main') {
    return firstMenu?.path
  }
})

export default router
